﻿using AuthorityManagement.Helper;
using AuthorityManagement.Model;
using AuthorityManagement.Model.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Mapster;
using AuthorityManagement.Quartz;
using System.Threading;
using Quartz;

namespace AuthorityManagement.Controllers
{
    /// <summary>
    /// WeatherForecast控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
        private readonly ISqlSugarClient _Db;
        private readonly ILogger<WeatherForecastController> _logger;
        private readonly JwtHelper _jwtHelper;
        private readonly IConfiguration _configuration;
        private readonly IScheduler _scheduler;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, JwtHelper jwtHelper, IConfiguration configuration, ISqlSugarClient db, IScheduler scheduler)
        {
            _logger = logger;
            _jwtHelper = jwtHelper;
            _configuration = configuration;
            _Db = db;
            _scheduler = scheduler;
        }

        ///// <summary>
        ///// 获取Get
        ///// </summary>
        ///// <returns></returns>
        //[Authorize]
        //[HttpGet]
        //public IEnumerable<WeatherForecast> Get()
        //{
        //    var rng = new Random();
        //    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        //    {
        //        Date = DateTime.Now.AddDays(index),
        //        TemperatureC = rng.Next(-20, 55),
        //        Summary = Summaries[rng.Next(Summaries.Length)]
        //    })
        //    .ToArray();
        //}

        /// <summary>
        ///获取Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> GetToken()
        {
            string test = _configuration["JWT:Issuer"];
            return _jwtHelper.CreateToken();
            return "Test Authorize";
        }

        /// <summary>
        /// 权限测试
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("test")]
        public ActionResult<string> GetTest()
        {
            return "Test Authorize";
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        //[Authorize]
        [HttpPost("GetUserList")]
        public dynamic GetUserList([FromBody] UserListQueryInput input)
        {
            var data = _Db.Queryable<User>().Select(it => new UserUpInput
            {
                UserCode = it.UserCode,
                UserName = it.UserName,
                Address = it.Address,
                Age = it.Age,
                Sex = it.Sex,
                Status = it.Status,
                Url = it.Url,
                Phone = it.Phone,
                Remark = it.Remark,
                Sort = it.Sort,
                Email = it.Email,
            }).ToPageList(input.currentpage, input.pagesize);
            return new { list = data, count = data.Count };
        }

        /// <summary>
        /// 获取树形菜单
        /// </summary>
        /// <returns></returns>
        //[Authorize]
        [AllowAnonymous]
        [HttpGet("GetTreeMenu")]
        public List<MenuDto> GetTreeMenu()
        {
            //返回的数据树
            List<MenuDto> partmenu = new List<MenuDto>();
            var partmenulist = _Db.Queryable<Menu>().Where(it => it.ParentId == "0").Select(it => new MenuDto { MenuCode = it.MenuCode, MenuName = it.MenuName, URL = it.URL, ParentId = it.ParentId, Ischild = it.IsChild }).ToList();

            foreach (var item in partmenulist)
            {
                //获取二级菜单的数据
                var childmenlist = _Db.Queryable<Menu>().Where(it => it.ParentId == item.MenuCode).Select(it => new MenuDto { MenuCode = it.MenuCode, MenuName = it.MenuName, URL = it.URL, ParentId = it.ParentId, Ischild = it.IsChild }).ToList();
                if (childmenlist.Count != 0)
                {
                    foreach (var item1 in childmenlist)
                    {
                        var menlist = _Db.Queryable<Menu>().Where(it => it.ParentId == item1.MenuCode).Select(it => new MenuDto { MenuCode = it.MenuCode, MenuName = it.MenuName, URL = it.URL, ParentId = it.ParentId, Ischild = it.IsChild }).ToList();
                        if (menlist.Count != 0)
                        {
                            foreach (var item2 in menlist)
                            {
                                item1.Menuchild.Add(item2);
                                item2.Menuchild = null;
                            }
                        }
                        else
                        {
                            item1.Menuchild = null;
                        }

                        item.Menuchild.Add(item1);
                    }
                }
                else
                {
                    item.Menuchild = null;
                }
                partmenu.Add(item);
            }
            return partmenu;

            //三级菜单
            //获取所有菜单数据
            //var menuAll = _Db.Queryable<Menu>().Select(it => new Menu { MenuCode = it.MenuCode, MenuName = it.MenuName, URL = it.URL,ParentId=it.ParentId }).ToList();
            //List<MenuDto> menudtolist = new List<MenuDto>();
            //foreach (var menu in menuAll)
            //{
            //    var menudtomp = menu.Adapt<MenuDto>();
            //    menudtolist.Add(menudtomp);
            //}
            //foreach (var menu in menudtolist)
            //{
            //    menu.Menuchild = menudtolist.FindAll(i => i.ParentId == menu.MenuCode);
            //}
            //menudtolist = menudtolist.FindAll(m => m.ParentId == "0");
            //return menudtolist;
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="Password">密码</param>
        /// <returns></returns>
        [HttpPost("Login")]
        public dynamic Login([FromHeader] LoginDto logindto)
        {
            //错误信息
            string Message = "";
            //根据传过来的用户名在数据库中查找是否有这个人
            var Userlist = _Db.Queryable<User>().Where(it => it.UserName == logindto.UserName && it.DeleteMark == null).Select(it => new { UserName = it.UserName, Password = it.PassWord }).ToList().FirstOrDefault();
            if (Userlist != null)
            {
                if (Userlist.Password == logindto.Password)
                {
                    var token = _jwtHelper.CreateToken();
                    //Message = "登录成功!";
                    //return new { token = token, message = Message,success=true };
                    return new { token = token, success = true };
                }
                else
                {
                    Message = "密码错误!";
                }
            }
            else
            {
                Message = "该用户不存在!";
            }
            return new { token = "", Message = Message, success = false };

        }

        /// <summary>
        /// 获取角色名称
        /// </summary>
        /// <returns></returns>
        [Route("GetRoleName")]
        [HttpPost]
        public dynamic GetRoleName()
        {
            //获取角色集合
            var roleList = _Db.Queryable<Role>().Select(it => new Role { RoleCode = it.RoleCode, RoleName = it.RoleName }).ToList();
            List<RoleDto> roledto = new List<RoleDto>();
            foreach (var item in roleList)
            {
                var rolename = new RoleDto { roleCode = item.RoleCode, roleName = item.RoleName };
                roledto.Add(rolename);
            }
            return Ok(roledto);
        }

        [HttpPost("SendMessageTest")]
        public async Task<IActionResult> SendMessageTest(string triggerKey)
        {
            var parts = triggerKey.Split('.');
            if (parts.Length != 2)
            {
                return BadRequest("Invalid triggerKey format. Expected 'name.group'.");
            }

            var triggerName = parts[0];
            var triggerGroup = parts[1];

            // 创建一个TriggerKey对象  
            var key = new TriggerKey(triggerName, triggerGroup);

            // 尝试从调度器中检索触发器  
            ITrigger trigger = await _scheduler.GetTrigger(key, CancellationToken.None);

            if (trigger == null)
            {
                return NotFound($"Trigger with key '{triggerKey}' not found.");
            }

            // 这里你可以根据需要修改触发器（比如重新调度它）  
            // 但在这个示例中，我们只是返回触发器的一些信息  

            // 返回触发器信息（或者你可能想在这里重新调度触发器并返回结果）  
            return Ok(new
            {
                TriggerName = trigger.Key.Name,
                TriggerGroup = trigger.Key.Group,
                // 可以添加更多触发器相关的属性  
            });

        }
        public class MenuDto
        {
            /// <summary>
            /// 菜单编码
            /// </summary>
            public string MenuCode { get; set; }
            /// <summary>
            /// 菜单描述
            /// </summary>
            public string MenuName { get; set; }

            /// <summary>
            /// URL
            /// </summary>
            public string URL { get; set; }
            /// <summary>
            /// 父级id
            /// </summary>
            public string ParentId { get; set; }
            /// <summary>
            /// 子级菜单
            /// </summary>
            public List<MenuDto>? Menuchild { get; set; } = new List<MenuDto>();

            /// <summary>
            /// 是否有子集
            /// </summary>
            public string Ischild { get; set; }
        }

        /// <summary>
        /// 登录Dto
        /// </summary>
        public class LoginDto
        {
            /// <summary>
            /// 用户名
            /// </summary>
            public string UserName { get; set; }

            /// <summary>
            /// 密码
            /// </summary>
            public string Password { get; set; }
        }

        /// <summary>
        /// 角色Dto
        /// </summary>
        public class RoleDto
        {
            /// <summary>
            /// id
            /// </summary>
            public string id { get; set; }

            /// <summary>
            /// 角色编码
            /// </summary>
            public string roleCode { get; set; }

            /// <summary>
            /// 角色名称
            /// </summary>
            public string roleName { get; set; }
        }
    }
}
